﻿using Castle.DynamicProxy;
using Microsoft.Extensions.Logging;
using Simple.Tools;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Simple.Common
/// <summary>
/// 版 本 钢易智企2.0 V 2.0.0 钢易智企2.0
/// Copyright (c) 2023 杭州钢易科技有限公司
/// 创建人：曾东明
/// 日 期：2024
/// 描 述：
/// </summary>
{
	public class CustomAutofacAop: IInterceptor
	{
		[Autowired]
		private ILogger<CustomAutofacAop> logger { get; set; }

		[Autowired]

		protected ISqlSugarClient client { get; set; }
		public CustomAutofacAop()
		{
		}

		/// <summary>
		/// 打印调用调用服务所传输的参数
		/// </summary>
		/// <param name="invocation"></param>
		/// 

		public void Intercept(IInvocation invocation)
		{
			#region Parameter Print
			StringBuilder paramsMessage = new StringBuilder($"\t\tNow time:{DateTime.Now};\n\t\t\tThe location where the request is processed:{invocation.TargetType.FullName},{invocation.Method.Name}");
			ParameterInfo[] parameterInfos = invocation.Method.GetParameters();
			object[] arguments = invocation.Arguments;
			for (int i = 0; i < parameterInfos.Length; i++)
			{
				if (arguments[i] == null)
				{
					continue;
				}
				Type type = arguments[i].GetType();
				paramsMessage.Append($"\n\t\t\tArgument:{type.FullName};");
				if (type.IsClass && type != typeof(string))
				{
					bool isArray = type.ToString().Contains(typeof(List<>).ToString().Split('`')[0]);

					foreach (var prop in type.GetProperties())
					{
						if (isArray)
						{
						}
						else
						{
							paramsMessage.Append($"\n\t\t{prop.Name}:{prop.GetValue(arguments[i])};");
						}
					}

				}
				else
				{
					paramsMessage.Append($"\n\t\t{parameterInfos[i].Name}:{arguments[i]}");
				}
			}
			logger.LogInformation(paramsMessage.ToString());
			#endregion


			#region 事务


			TransactionAttribute transaction=invocation.Method.GetCustomAttribute<TransactionAttribute>();
			if (transaction==null)
			{
				 transaction = invocation.MethodInvocationTarget.GetCustomAttribute<TransactionAttribute>();
			}
			bool IsTransaction=transaction != null;
			if (IsTransaction)
			{
				client.Ado.BeginTran();
			}
			try
			{
				invocation.Proceed();
			}
			catch (Exception ex)
			{
				logger.LogError(ex.Message);
				logger.LogError(ex.StackTrace);
				if (IsTransaction)
				{
					client.Ado.RollbackTran();
				}
				throw ex;
			}
			if (IsTransaction)
			{
				client.Ado.CommitTran();
			}

			#endregion
		}
	}
}
